#include "Indexer.hpp"

Indexer::Indexer(Database* d, ConfigManager* c, bool m) : db(d), cm(c), monitor(m) {
    if(m) enableMonitoring();
}

Indexer::~Indexer() {
    if(fsw!=NULL) delete fsw;
}

void Indexer::search(QString dir) {
    QDir d(dir);
    QFileInfoList list = d.entryInfoList();
    for (int i=0;i<list.count();i++) {
        QFileInfo info = list[i];
        QString filepath = info.filePath();
        if (info.isDir())
            if (info.fileName()!=".." && info.fileName()!=".") search(filepath);
        else {
            /// @todo process files (filter format, get tag and add to db)
            if(formats.split(",").contains(info.suffix())) {
                AudioFile af(info.absoluteFilePath());
                if(af.getTime()<cm->getMinTime() || (cm->getMaxTime()!=0 && af.getTime()>cm->getMaxTime())) continue;
                if(af.isTagEmpty() && cm->hasTags()) continue;
                if(af.getChannels()<cm->getMinChannels() || (cm->getMaxChannels()!=0 && af.getChannels()>cm->getMaxChannels())) continue;
                if(af.getBitrate()<cm->getMinBitrate() || (cm->getMaxBitrate()!=0 && af.getBitrate()>cm->getMaxBitrate())) continue;
                db->set(&af);
            }
        }
    }
}

void Indexer::deleteMissing() {
}
void Indexer::removeMissmatch() {
    //db->removeMissmatch();
}

void Indexer::run() {
    formats=cm->getAuthorizedFormats();
    deleteMissing();
    for(int i=0; i<cm->getCollection()->size(); i++) search(cm->getCollection()->at(i));
}

void Indexer::enableMonitoring() {
    fsw=new QFileSystemWatcher();
}

void Indexer::disableMonitoring() {
    delete fsw;
    fsw=NULL;
}

void Indexer::updateFile(const QString& path) {
    AudioFile f(path);
    db->set(&f);
}

void Indexer::updateFolder(const QString& path) {
    search(path);
}

